package com.intellagric.service.login;

import com.intellagric.common.bean.ResponseMessage;

import com.intellagric.interfaces.login.LoginService;
import com.intellagric.mapper.SysMenuMapper;
import com.intellagric.mapper.SysUserMapper;
import com.intellagric.mapper.SysUserRoleMapper;
import com.intellagric.pojo.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: zhy
 * @Date: 2018/10/6
 * @Description: 用户登录接口实现类
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
//
//    @Autowired
//    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

//    @Autowired
//    private JedisClient jedisClient;


    @Override
    public ResponseMessage login(HttpServletRequest request, String username, String password) {
        //判断登录数据是否正确
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andLoginNameEqualTo(username);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(userExample);

        if (sysUsers.size() == 0 || sysUsers == null) {
            return ResponseMessage.fail("用户名或者密码错误");
        }
        SysUser user = sysUsers.get(0);
        if (!user.getPassword().equals(password)) {
            return ResponseMessage.fail("用户名或者密码错误");
        }

        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(user.getId());
        List<SysUserRoleKey> sysUserRoleKeys = sysUserRoleMapper.selectByExample(sysUserRoleExample);
        if (sysUserRoleKeys.size() != 0) {
            //查询角色的权限信息
            String roleId = sysUserRoleKeys.get(0).getRoleId();

            user.setRoleId(roleId);
        }
        //cookie不能放置中文
        user.setUpdateDate(null);
        user.setCreateDate(null);
        user.setLoginName("");
        user.setSex("");
        user.setRealname("");
        user.setPassword(null);
        //获取客户端ip
        String ip=getClientIp(request);
        user.setLoginIp(ip);


    //拿到一个cookieId,如果不等于null，说明已经登陆过，

        return ResponseMessage.success("登录成功").add("user", JSONObject.fromObject(user).toString());
    }


    public String getClientIp(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
//        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
//            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
//            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
//            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
//            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
//            System.out.println("getRemoteAddr ip: " + ip);
        }

        return ip;


    }

    /**
     * 通过角色id查询菜单列表信息,并生成菜单树
     * @return LayuiDataGridResult
     */
//    private List<SysMenu> getPermissionByRole(String[] menuIds){
//        //获取所有的角色的权限列表
//        List<SysMenu> menuList = new ArrayList<>();
//        for (String menuId:menuIds) {
//            menuList.add(sysMenuMapper.selectByPrimaryKey(menuId));
//        }
//        Collections.sort(menuList, new Comparator<SysMenu>() {
//            @Override
//            public int compare(SysMenu o1, SysMenu o2) {
//                return o1.getSort() > o2.getSort() ? 1 : -1;//升序排列
//            }
//        });
//
//        //查询其中的顶级分类
//        List<SysMenu> rootMenuList = new ArrayList<>();
//        for (SysMenu menu: menuList) {
//            if (menu.getParentId().equals("0")) {
//                rootMenuList.add(menu);
//            }
//        }
//
//        //生成树形菜单数据，为一级菜单设置子菜单，getChild是递归调用的
//        for (SysMenu menu : rootMenuList) {
//            menu.setChildren(getChild(menu.getId(), menuList));
//        }
//
//        return rootMenuList;
//    }
//
//    private List<SysMenu> getChild(String id, List<SysMenu> menuList) {
//        // 子菜单
//        List<SysMenu> childList = new ArrayList<>();
//
//        // 遍历所有节点，将父菜单id与传过来的id比较
//        for (SysMenu Menu : menuList) {
//            if (Menu.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
//                if (Menu.getParentId().equals(id)) {
//                    childList.add(Menu);
//                }
//            }
//        }
//        // 把子菜单的子菜单再循环一遍
//        for (SysMenu Menu : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
//            // 递归
//            Menu.setChildren(getChild(Menu.getId(), menuList));
//        } // 递归退出条件
//        if (childList.size() == 0) {
//            return null;
//        }
//        return childList;
//    }
}
